package com.xinqi.common.log.asynclog.aspect;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xinqi.common.core.utils.JsonUtils;
import com.xinqi.common.core.utils.ServletUtils;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.log.asynclog.annotation.AsyncLog;
import com.xinqi.common.log.asynclog.enums.AsyncStatus;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.modules.sys.log.client.AsyncLogClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 异步操作日志记录处理
 *
 * @author dzy
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class AsyncLogAspect {

    private final AsyncLogClient asyncLogClient;

    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(asyncLog)")
    public void doAfterReturning(JoinPoint joinPoint, AsyncLog asyncLog) {
        saveAsyncLog(joinPoint, asyncLog, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(asyncLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, AsyncLog asyncLog, Exception e) {
        saveAsyncLog(joinPoint, asyncLog, e.toString());
    }

    /**
     * 添加异步日志记录
     */
    private void saveAsyncLog(JoinPoint joinPoint, AsyncLog asyncLog, String error) {
        Map<String, Object> logDTO = new HashMap<>();
        logDTO.put("title", asyncLog.title());
        logDTO.put("type", asyncLog.asyncType().getCode());
        logDTO.put("operaType", asyncLog.operatorType().getCode());
        logDTO.put("operatorIp", ServletUtils.getClientIP());
        logDTO.put("operatorUrl", StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        try {
            logDTO.put("operatorId", LoginHelper.getUserId());
        } catch (Exception e) {
            logDTO.put("operatorId", 1L);
        }
        String requestMethod = ServletUtils.getRequest().getMethod();
        if (Objects.equals(HttpMethod.PUT.name(), requestMethod) || Objects.equals(HttpMethod.POST.name(), requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            logDTO.put("paramJson", params);
        } else {
            Map<String, String> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
            MapUtil.removeAny(paramsMap, EXCLUDE_PROPERTIES);
            logDTO.put("paramJson", JsonUtils.toJsonString(paramsMap));
        }
        logDTO.put("status", asyncLog.asyncStatus().getCode());
        logDTO.put("errorMsg", asyncLog.errorMsg());
        if (StringUtils.isNotEmpty(error)) {
            logDTO.put("status", AsyncStatus.FAIL.getCode());
            logDTO.put("errorMsg", error);
        }
        asyncLogClient.saveAsyncLog(logDTO);
    }


    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        String str = JsonUtils.toJsonString(o);
                        Dict dict = JsonUtils.parseMap(str);
                        if (MapUtil.isNotEmpty(dict)) {
                            MapUtil.removeAny(dict, EXCLUDE_PROPERTIES);
                            str = JsonUtils.toJsonString(dict);
                        }
                        params.append(str).append(" ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse || o instanceof BindingResult;
    }

}
